package com.happy.ibidding.controller;

import com.happy.ibidding.bean.Favour;
import com.happy.ibidding.dao.FavorRepository;
import com.happy.ibidding.service.AskService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("api/favor")
public class FavorController {

    final private FavorRepository favorRepository;

    final private AskService askService;

    public FavorController(FavorRepository favorRepository, AskService askService) {
        this.favorRepository = favorRepository;
        this.askService = askService;
    }


    @GetMapping("/add/{userId}/{askId}")
    public void addfavor(@PathVariable String userId, @PathVariable String askId) {

        if (this.isfavor(userId, askId)) {
            return;
        }


        this.favorRepository
                .save(
                        Favour.builder().askId(askId).userId(userId)
                                .favorTime(System.currentTimeMillis()).build());
    }

    @GetMapping("/is/{userId}/{askId}")
    public boolean isfavor(@PathVariable String userId, @PathVariable String askId) {
        return Objects.nonNull(this.favorRepository.findByAskIdAndUserId(askId, userId));
    }

    @GetMapping("/{userId}/all")
    public List<Favour> viewAll(@PathVariable String userId) {
        List<Favour> favourList = this.favorRepository.findByUserId(userId);

        favourList.parallelStream().forEach(each -> each.setAsk(askService.view(each.getAskId())));

        return favourList;
    }
}
